package com.atguigu.spzx.manager.service.impl;

import cn.hutool.json.JSONUtil;
import com.atguigu.common.service.constant.RedisConstant;
import com.atguigu.common.service.exception.SpzxException;
import com.atguigu.spzx.manager.mapper.SysRoleMapper;
import com.atguigu.spzx.manager.mapper.SysUserRoleMapper;
import com.atguigu.spzx.model.dto.system.SysUserDto;
import com.atguigu.spzx.model.entity.system.SysRole;
import com.atguigu.spzx.model.entity.system.SysUserAuthContextUtil;
import com.atguigu.spzx.manager.mapper.SysUserMapper;
import com.atguigu.spzx.manager.service.SysUserService;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.base.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.LoginVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author yaya
 * @Create 2024/6/18 18:21
 * Description:
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public LoginVo login(LoginDto loginDto) {
        String captcha = loginDto.getCaptcha();
        String codeKey = loginDto.getCodeKey();
        if (!StringUtils.hasText(captcha)) {
            throw new SpzxException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }
        String captchaForRedis = redisTemplate.opsForValue().get(codeKey);
        if (!StringUtils.hasText(captchaForRedis)) {
            throw new SpzxException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        if (!captcha.equals(captchaForRedis)) {
            throw new SpzxException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }

        // 验证通过则删除codeKey，防止二次验证
        redisTemplate.delete(codeKey);

        LoginVo loginVo = new LoginVo();
        String userName = loginDto.getUserName();
        String password = loginDto.getPassword();
        if (!StringUtils.hasText(password) || !StringUtils.hasText(userName)) {
            throw new SpzxException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }

        SysUser sysUser = sysUserMapper.selectByUsername(userName);
        if (sysUser == null) {
            throw new SpzxException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }

        String DBPassword = sysUser.getPassword();
        String md5InputPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!md5InputPassword.equals(DBPassword)) {
            throw new SpzxException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }

        // String token = JwtUtil.createToken(sysUser.getId(), userName);

        String token = UUID.randomUUID().toString().replace("-", "");
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + token;
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(sysUser),
                2, TimeUnit.DAYS);

        loginVo.setToken(token);
        loginVo.setRefresh_token("");

        return loginVo;
    }

    @Override
    public SysUser getUserInfo(String token) {
        return SysUserAuthContextUtil.get();
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete(RedisConstant.ADMIN_LOGIN_PREFIX + token);
    }

    @Override
    public PageInfo<SysUser> findByPage(Integer pageNum, Integer pageSize, SysUserDto sysUserDto) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysUser> sysUserList = sysUserMapper.selectByPage(sysUserDto);
        return new PageInfo<SysUser>(sysUserList);
    }

    @Override
    public void savaSysUser(SysUser sysUser) {
        sysUserMapper.insertSysUser(sysUser);
    }

    @Override
    public void updateSysUser(SysUser sysUser) {
        sysUserMapper.updateSysUser(sysUser);
    }

    @Override
    public void deleteById(Long id) {
        sysUserMapper.deleteById(id);
    }

    @Override
    public Map<String, Object> getAllRoleList(Long currentUserId) {
        List<SysRole> sysRoleList = sysRoleMapper.selectAll();

        List<Long> userRoleIds = sysUserRoleMapper.selectRoleIdByUserId(currentUserId);

        Map<String, Object> map = new HashMap<>();
        map.put("allRoles", sysRoleList);
        map.put("userRoleIds", userRoleIds);
        return map;
    }
}
